/**
 * @file Axios的Vue插件（添加全局请求/响应拦截器）
 */

// https://github.com/mzabriskie/axios
import axios from 'axios'

const globalConfig = require('../../globalConfig');
axios.interceptors.request.use(function(config) {
    let gateway_token = getUrlKey('gateway_token');

    if (typeof gateway_token != 'undefined' && typeof localStorage.getItem('token')=='undefined' ) {

        localStorage.setItem('token', gateway_token);
    }
    config.headers['X-Requested-With'] = "XMLHttpRequest";
    const token = localStorage.getItem("token");
    //console.log(token);
    if(token) {
        config.headers['x-auth-token'] = token;

    }
  //  config.headers['x-client-project-code'] = globalConfig.servers.systemId;

    return config;
}, function(error) {
    return Promise.reject(error);
});
let getUrlKey=function (name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
};
// 拦截响应response，并做一些错误处理
axios.interceptors.response.use((response) => {
	if(response.status ===200 && response.data && response.data.code === 401) {
		if(!window.location.href.startsWith(response.data.stackMsg)) {
            window.location.href = response.data.stackMsg + "?redirceUrl=" + encodeURIComponent(window.location.href);

        }
	}

	//获取返回的TOKEN
	const token=response.headers['x-auth-token'];

    if(token) {
		//将续期的TOKEN存起来
        localStorage.setItem("token",token) ;
    }
    // 这里是填写处理信息
	return response;
}, (err) => { // 这里是返回状态码不为200时候的错误处理
	console.log(err);
	if(err && err.response) {
		switch(err.response.data.code) {
			case 400:
				err.message = '请求错误';
				break;

			case 401:
				err.message = '未授权，请登录';
				break;

			case 403:
				err.message = '无权限';
				break;

			case 404:
				err.message = `请求地址出错: ${err.response.config.url}`;
				break;

			case 408:
				err.message = '请求超时';
				break;

			case 500:
				err.message = '服务器内部错误';
				break;

			case 501:
				err.message = '服务未实现';
				break;

			case 502:
				err.message = '网关错误';
				break;

			case 503:
				err.message = '服务不可用';
				break;

			case 504:
				err.message = '网关超时';
				break;

			case 505:
				err.message = 'HTTP版本不受支持';
				break;

			default:
		}
	}
	Vue.prototype.$message.error(err.response.data.msg!=null?err.response.data.msg:err.message);
	return Promise.reject(err)
});

axios.install = (Vue) => {
	Vue.prototype.$axios = axios
};
export default axios
